<?php
declare(strict_types=1);

namespace app\model;

use support\Model;

/**
 * GpsRealtime 实时位置表 ORM
 * 主键：imei+gpstime
 */
class GpsRealtime extends Model
{
    protected $table = 'gps_realtime';
    public $timestamps = false;
    protected $primaryKey = null;
    public $incrementing = false;
    protected $fillable = [
        'imei','gpstime','wgs84_lat','wgs84_lon','speed','direction','altitude','alarm','acc','located','geom_wgs84','created_at'
    ];

    protected static function pdo(): \PDO
    {
        $dsn = sprintf(
            'mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4',
            env('DB_HOST', '127.0.0.1'),
            (int)env('DB_PORT', 3306),
            env('DB_DATABASE', 'saas_gps_service')
        );
        $pdo = new \PDO($dsn, env('DB_USERNAME', 'root'), env('DB_PASSWORD', ''), [
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
            \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
            \PDO::ATTR_TIMEOUT => 5,
        ]);
        return $pdo;
    }

    public static function upsertRealtime(
        string $imei,
        float $wgsLat,
        float $wgsLon,
        int $speed,
        int $direction,
        ?int $altitude,
        int $alarm,
        int $acc,
        int $located,
        string $gpstime
    ): void {
        $sql = "INSERT INTO gps_realtime
            (imei,gpstime,wgs84_lat,wgs84_lon,speed,direction,altitude,alarm,acc,located,geom_wgs84,created_at)
            VALUES (?,?,?,?,?,?,?,?,?,?,ST_SRID(POINT(?,?),4326),NOW())
            ON DUPLICATE KEY UPDATE
              wgs84_lat=VALUES(wgs84_lat),wgs84_lon=VALUES(wgs84_lon),
              speed=VALUES(speed),direction=VALUES(direction),
              altitude=VALUES(altitude),alarm=VALUES(alarm),
              acc=VALUES(acc),located=VALUES(located),
              geom_wgs84=VALUES(geom_wgs84)";
        $stmt = self::pdo()->prepare($sql);
        $stmt->execute([$imei, $gpstime, $wgsLat, $wgsLon, $speed, $direction, $altitude, $alarm, $acc, $located, $wgsLon, $wgsLat]);
    }
}